package com.plugin.manage.service.impl;

import com.plugin.core.model.entity.SysMgrUser;
import com.plugin.manage.common.BizCode;
import com.plugin.manage.common.RespObj;
import com.plugin.manage.mapper.SysMgrUserMapper;
import com.plugin.manage.pojo.vo.SysUserVO;
import com.plugin.manage.security.JwtPayload;
import com.plugin.manage.security.JwtTokenUtil;
import com.plugin.manage.service.ISysAuthService;
import com.plugin.manage.test.AppDeepseek;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 系统认证服务实现类
 * 
 * @author mark
 */
@Slf4j
@Service
public class SysAuthServiceImpl implements ISysAuthService {

    @Value("${jwt.expiration}")
    private Long expiration;

    @Autowired
    private SysMgrUserMapper sysMgrUserMapper;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 用户登录
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespObj<?> login(String username, String password) {
        try {
            // 参数验证
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                return new RespObj<>().error(BizCode.NO_PARAM.getMessage());
            }

            SysMgrUser user = sysMgrUserMapper.selectByUsername(username);
            if (user == null) {
                return new RespObj<>().error(BizCode.NO_USER_ACCOUNT.getMessage());
            }

            // 验证密码
            if (!passwordEncoder.matches(password, user.getPassword())) {
                return new RespObj<>().error(BizCode.USERNAME_OR_PASSWORD_ERROR.getMessage());
            }

            // 检查用户状态 ( 0停用)
            if (0 == user.getAccountStatus()) {
                return new RespObj<>().error("用户已被禁用");
            }

            String token = jwtTokenUtil.generateToken(JwtPayload.createPayload(user, expiration));
            SysUserVO vo = SysUserVO.build(user);
            // 构建返回数据
            Map<String, Object> data = new HashMap<>();
            if(StringUtils.hasText(token)){
                data.put("token", token);
                data.put("userInfo", vo);
                log.info("------------------成功生成Token: {} ,token超时时间是: {} ----------------", token, expiration);
            }

            log.info("-------------用户: {} 登录成功--------------", username);
            return new RespObj<>().success(data);

        } catch (Exception e) {
            log.error("登录过程中发生异常", e);
            return new RespObj<>().error("登录失败，系统异常");
        }
    }

    /**
     * 用户注册
     */
    @Override
    public RespObj<?> register(String username, String password, String email, String phone) {
        try {
            // 参数验证
            if (!StringUtils.hasText(username) || !StringUtils.hasText(password)) {
                return new RespObj<>().error("用户名和密码不能为空");
            }

            // 检查用户名是否已存在
            SysMgrUser existUser = sysMgrUserMapper.selectByUsername(username);
            if (existUser != null) {
                return new RespObj<>().error("用户名已存在");
            }

            // 创建新用户
            SysMgrUser newUser = new SysMgrUser();
            newUser.setUsername(username);
            newUser.setPassword(passwordEncoder.encode(password));
            newUser.setEmail(email);
            newUser.setMobilePhone(phone);
            newUser.setAccountStatus(0); // 默认正常状态
            newUser.setUserType(1); // 默认普通用户
            newUser.setCreateTime(LocalDateTime.now());
            newUser.setDelFlag("0"); // 默认未删除

            // 保存用户
            int result = sysMgrUserMapper.insert(newUser);
            if (result > 0) {
                log.info("用户注册成功: {}", username);
                return new RespObj<>().success("注册成功");
            } else {
                return new RespObj<>().error("注册失败");
            }

        } catch (Exception e) {
            log.error("注册过程中发生异常", e);
            return new RespObj<>().error("注册失败，系统异常");
        }
    }
}
